const express = require('express')
const mysql = require('mysql')
const db = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456789',
  database: 'learner'
})

module.exports = function () {
  let router = express.Router()

  router.get('/', (req, res) => {
    db.query(`SELECT * FROM contact_table`, (err, data) => {
      if (err) {
        res.state(500).send('database error').end()
      } else {
        let contacts = {
          street: (data.length && data[0].street) || '暂无数据',
          phone: (data.length && data[0].phone) || '暂无数据',
          fax: (data.length && data[0].fax) || '暂无数据',
          email: (data.length && data[0].email) || '暂无数据',
          weibo: (data.length && data[0].weibo) || '暂无数据',
          wechat: (data.length && data[0].wechat) || '暂无数据',
          map: (data.length && data[0].map) || '暂无数据'
        }
        res.render('admin/contact.ejs', { contacts })
      }
    })
  })

  router.post('/', (req, res) => {
    let street = req.body.street
    let phone = req.body.phone
    let fax = req.body.fax
    let email = req.body.email
    let weibo = req.body.weibo
    let wechat = req.body.wechat
    let map = req.body.map
    db.query(`SELECT * FROM contact_table`, (err, data) => {
      if (err) {
        res.state(500).send('database error').end()
      } else if (data.length === 0) {
        // 无数据时新增
        db.query(`INSERT INTO contact_table (street, phone, fax, email, weibo, wechat, map) VALUE ('${street}', '${phone}', '${fax}', '${email}', '${weibo}', '${wechat}', '${map}')`, (err, data) => {
          if (err) {
            console.error(err)
            res.state(500).send('database error').end()
          } else {
            res.redirect('/admin/contact')
          }
        })
      } else {
        // 有数据时更新
        db.query(`UPDATE contact_table SET street='${street}', phone='${phone}', fax='${fax}', email='${email}', weibo='${weibo}', wechat='${wechat}', map='${map}' WHERE id=${data[0].id}`, (err, data) => {
          if (err) {
            console.error(err)
            res.state(500).send('database error').end()
          } else {
            res.redirect('/admin/contact')
          }
        })
      }
    })
  })

  return router
}
